package com.ruoyi.gateway.config;


import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled;
import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;
import com.alibaba.cloud.nacos.registry.NacosRegistration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.util.Set;

@Component
@ConditionalOnNacosDiscoveryEnabled

public class NacosRegisterOnWar implements ApplicationRunner {

    @Autowired
    private NacosRegistration registration;

    @Autowired
    private NacosAutoServiceRegistration nacosAutoServiceRegistration;

    @Value("${server.port}")
    Integer port;

    @Override
    public void run(ApplicationArguments args) {
        if (registration != null && port != null) {
             Integer registerPort = port;
            try {
                String tomcatPort = getTomcatPort();
                if(StringUtils.isNotBlank(tomcatPort)){
                    registerPort = new Integer(tomcatPort);
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("{nacos 注册} 获取外部Tomcat端口异常：");
            }
            registration.setPort(registerPort);
            nacosAutoServiceRegistration.start();
        }
    }

    /**
     *	获取外部tomcat端口
     */
    public String getTomcatPort() throws Exception {
        MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> objectNames = beanServer.queryNames(
                new ObjectName("*:type=Connector,*"),
                Query.match(Query.attr("protocol"),
                        Query.value("HTTP/1.1")));
        String port = "";
        for (ObjectName objectName : objectNames) {
            port = objectName.getKeyProperty("port");
            if(StringUtils.isNotBlank(port)){
                return port;
            }
        }
        return port;
    }
}

